import datetime
import json
from django.http import HttpResponseRedirect
from django.shortcuts import render
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.response import Response
from tools.comm import get_alipay
import random
from tools.myredis import mredis
from rest_framework import status
from rest_framework.generics import CreateAPIView,ListAPIView
from order.OrderSerializer import OrderSerializer
from rest_framework.permissions import IsAuthenticated
from order.models import OrderModel,OrderDetailsModel
from django.db import transaction
import uuid
from tools.myredis import mredis
import time
from goods.models import ProductModel
from user.models import UserModel
from tools.myMongo import monge_comm


class OrderCreateView(APIView):
    def post(self, request):
        try:
            data = request.data
            # print(data)
            # 假设从请求中获取用户ID，这里为了示例设为1
            userid = 1
            orderno = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(userid) + str(random.randint(10000, 99999))

            # 计算总价
            quantity = int(data.get('total_count', 0))
            unit_price = float(data.get('total_price', 0.0))
            total_price = quantity * unit_price  # 计算小计
            # 商品id从请求数据中获取
            product_id = data.get('product_id')
            product = ProductModel.objects.filter(id=product_id).first()
            if not product:
                return Response({'message': '商品不存在', 'code': 201})
            if product.count < quantity:
                return Response({'message': '库存不足', 'code': 201})

            # 创建订单字典
            order_dict = {
                "user": userid,
                "pay_type": 2,  # 默认支付类型为2（支付宝）
                "total_count": quantity,  # 总件数
                "total_price": total_price,
                "order_no": orderno,
                "order_status": 1,  # 默认状态为“未支付”
                "ordered_at": datetime.datetime.now(),  # 当前时间作为下单时间
                # "transaction_no": None
            }

            order = OrderModel.objects.create(
                user_id=order_dict['user'],
                pay_type=order_dict['pay_type'],
                total_count=order_dict['total_count'],
                total_price=order_dict['total_price'],
                order_no=orderno,
                ordered_at=order_dict['ordered_at'],
                order_status=order_dict['order_status'],
                transaction_no=str(random.randint(10000, 99999)) + orderno + str(order_dict['pay_type'])
            )
            print(order)
            # 判断order是否生成成功
            if not order:
                return Response({'message': '订单创建失败', 'code': 201})

            # 更新用户积分
            order = OrderModel.objects.filter(order_no=int(orderno)).first()
            user = order.user
            total = float(order.total_price)
            tscore = user.tscore
            UserModel.objects.filter(id=user.id).update(tscore=tscore + (total / 10))

            # 减少商品库存
            product.count -= quantity
            product.save()

            # 生成订单加入队列，半小时没支付订单处理
            mredis.zset_zadd('ordercancle', int(time.time()), orderno)
            return Response({'order_id': order.id, 'message': '订单创建成功', 'code': 200})

        except ValueError as e:
            return Response({'error': '数据类型错误'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(e)  # 打印错误信息
            return Response({'error': '未知错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# 订单列表
class OrderListView(APIView):
    # permission_classes = [IsAuthenticated]
    def get(self, request):
        user = request.query_params.get('user')
        # print('---------')
        # print(user)
        # 根据当前用户查询全部订单
        query_set = OrderModel.objects.filter(user=user)
        order_ser = OrderSerializer(instance=query_set, many=True)
        print(order_ser.data)
        return Response({'data': order_ser.data, 'code': 200})


# 支付宝支付
class Pay(APIView):
    def post(self, request):
        data = request.data
        orderId = data['orderId']
        # print(orderId)
        # 查询订单
        pay = get_alipay()
        # 根据订单ID查询订单价格和订单号
        order = OrderModel.objects.filter(pk=orderId).first()
        print(order.total_price, order.order_no)
        pay_money = order.total_price
        order_no = order.order_no
        # pay_money = 100
        query_params = pay.direct_pay(
            subject="宠物商品支付",  # 商品简单描述
            out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(pay_money),  # 交易金额(单位: 元 保留俩位小数)
        )
        payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)

        return Response({"code": 200, 'url': payUrl})


# 支付宝回调
class Alipaycallback(APIView):
    def get(self, request):
        data = request.GET
        mes = {k: v for k, v in data.items()}
        # print(mes)
        # 验证签名
        pay = get_alipay()
        sign = mes.pop('sign')
        flag = pay.verify(mes, sign)
        if flag:
            # print("####")
            # print(data)
            orderno = data['out_trade_no']

            # 创建保存点
            save_id = transaction.savepoint()
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()  # 记录了当前数据库的状态
                try:
                    # 更新订单状态
                    OrderModel.objects.filter(order_no=int(orderno)).update(order_status=2)
                    transaction.savepoint_commit(save_id)
                except:
                    transaction.savepoint_rollback(save_id)
                finally:
                    OrderModel.objects.filter(order_no=int(orderno)).update(order_status=2)

            # 将支付过的订单删除
            mredis.zset_zrem('ordercancle', orderno)
            # 加入成功队列表中，后续异步分配及操作
            # mredis.list_push('ordersuccess', orderno)
            # 通过不通过重定向到vue页面，提示订单不存在
            # 如果通过从data中获取订单号和支付宝流水号
            # 判断支付状态，如果成功，订单号写入队列
            return HttpResponseRedirect("http://localhost:8080/#/payroll")
        return Response({"code": 200})


# 订单评价
class OrderCommentView(APIView):
    def post(self, request):
        data = request.data
        comm_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(10000, 99999))
        user_id = 1
        order_id = data.get('order_id')
        print(order_id, type(order_id))
        comment = data.get('comment')
        grade = data.get('grade')
        pid = data.get('pid')
        if not pid:
            pid = 0

        document = {
            "comm_id": comm_id,
            "user_id": str(user_id),
            "order_id": order_id,
            "comment": comment,
            "grade": grade,
            "pid": pid
        }

        ret = monge_comm.insert_one(document)
        if ret.inserted_id:
            return Response({"code": 200, "message": "评价成功"})
        return Response({"code": 201, "message": "评价失败"})


# 订单评论查询
class OrderCommentQueryView(APIView):
    def get(self, request):
        order_id = request.query_params.get('order_id')
        print(order_id, type(order_id))
        quy_list = []
        for row in monge_comm.find({"order_id": order_id}, {"_id": 0}):
            quy_list.append(row)
        if quy_list:
            return Response({"data": quy_list, "code": 200})

        return Response({"msg": "暂无评论", "code": 201})


# 用户评论查询
class UserCommentQueryView(APIView):
    def get(self, request):
        user_id = request.query_params.get('user')
        print(user_id, type(user_id))
        quy_list = []
        for row in monge_comm.find({"user_id": str(user_id)}, {"_id": 0}):
            quy_list.append(row)
        if quy_list:
            return Response({"data": quy_list, "code": 200})

        return Response({"msg": "暂无评论", "code": 201})